var CreateOutOrder = function () {
  var template = /*html*/ `
    <div class="create-out-order" v-loading.fullscreen.lock="loading">
      <div class="title" style="text-align:center;font-size:20px;margin-bottom:20px;">生成外协单</div>
      <el-form :model="order" label-width="100px">
        <el-form-item label="订单编号" prop="orderId">
          <page-select filterable v-if="canSelectOrder" :options="orderList" v-model="order.orderId" class="form-input" :disabled="orderLoading"
            @change="orderChange" value-field="orderId" label-field="orderId" popper-class="orderSelectPopover" :filter-method="orderFilterMehod">
            <template slot-scope="scope">
              <el-option v-for="order in scope.options" :key="order.orderId" :value="order.orderId" :label="order.orderId">
                <div class="create-order-select-item">
                  <span style="width:145px;">{{order.orderId}}</span>
                  <span style="min-width:145px;">{{order.companyOrderId}}</span>
                  <span style="min-width:100px;">{{order.factoryId}}</span>
                  <span style="min-width:50px;">{{order.customerId}}</span>
                </div>
              </el-option>
            </template>
          </page-select>
          <span v-else>{{order.orderId}}</span>
        </el-form-item>

        <template v-if="selectOrder!==null">
        <el-form-item label="公司订单编号">
          <span>{{selectOrder.companyOrderId}}</span>
        </el-form-item>
        <el-form-item label="工厂型号">
          <span>{{selectOrder.factoryId}}</span>
        </el-form-item>
        <el-form-item label="客户型号">
          <span>{{selectOrder.customerId}}</span>
        </el-form-item>
        </template>

        <el-form-item label="供应商" prop="supplier">
          <el-select filterable v-model="order.supplier" value-key="id" class="form-input" @change="supplierChange" :disabled="technologyLoading">
            <el-option v-for="supplier in supplierList" :key="supplier.id" :value="supplier" :label="supplier.supplierName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加工工艺" prop="technology">
          <el-select filterable v-model="order.technology" class="form-input" @change="technologyChange" :loading="technologyLoading">
            <el-option v-for="prodCycle in prodCycleList" :key="prodCycle.id" :value="prodCycle.technology" :label="prodCycle.technology"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流程周期" prop="flowCycle">
          <el-input-number v-model="order.flowCycle" class="form-input" :min="1" controls-position="right" :precision="0"></el-input-number>
        </el-form-item>
        <el-form-item label="计价单位" prop="valuationUint">
          <el-input v-model="order.valuationUint" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="加工对象" prop="maching">
          <el-select filterable v-model="order.maching" class="form-input" :loading="orderLoading" @change="machingChange">
            <template v-if="order.technology!==''">
              <el-option v-for="(maching,index) in machingList" :key="'maching_'+index" :value="maching.value" :label="maching.label"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item v-if="order.maching!==''" label="是否电镀" prop="hasEle">
          <el-select v-if="order.canEle" v-model="order.hasEle" class="form-input">
            <el-option :value="false" label="否"></el-option>
            <el-option :value="true" label="是"></el-option>
          </el-select>
          <span v-else>{{order.hasEle?'是':'否'}}</span>
        </el-form-item>

        <material-out-order ref="materialOrder" :detail-list="orderDetail" :order="order" :precision="valuationCountPrecision">
        </material-out-order>
        <electroplate-out-order ref="electroplateOrder" :detail-list="orderDetail" :ele-data="eleOrderData" :order="order" :precision="valuationCountPrecision">
        </electroplate-out-order>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="order.remark" class="textarea-autosize" type="textarea" :autosize="true" resize="none"></el-input>
        </el-form-item>
      </el-form>

      <div style="text-align: center;">
        <el-button type="primary" @click="createOrder(false)">生成外协单</el-button>
        <el-button :disableld="!hasApproval" type="primary" @click="createOrder(true)">审核过账</el-button>
      </div>
    </div>
  `;

  return {
    props: {
      orderId: String
    },

    watch: {
      'order.valuationUint': function (unit) {
        var valuationCountPrecision = SysUtil.getMaterialNumberPrecision(unit, 4);
        this.valuationCountPrecision = valuationCountPrecision;
      }
    },

    data: function () {
      return {
        loading: false,
        technologyLoading: false,
        orderLoading: false,
        canSelectOrder: this.orderId === undefined,
        order: this.getInitOrder(),
        selectOrder: null,
        valuationCountPrecision: 0,
        materialMachingMap: {},
        orderList: [],
        supplierList: [],
        prodCycleList: [],
        detailList: [],
        orderDetail: [],
        machingList: [],
        eleOrderData: {},
        hasApproval: false
      };
    },
    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.checkApprovalAuthority(),
        this.setMaterialMachingMap(),
        this.setOrderList(),
        this.setSupplierList()
      ]).then(function () {
        self.loading = false;

        var orderId = self.order.orderId;
        if (orderId === '') {
          return;
        }
        var orderList = self.orderList;
        var selectOrder = _.find(orderList, {
          orderId: orderId
        });
        if (selectOrder === undefined) {
          self.order.orderId = '';
          self.canSelectOrder = true;
          return;
        }
        self.orderChange();
      }).catch(function () {
        self.loading = false;
      });
    },
    methods: {
      getInitOrder: function () {
        var orderId = this.orderId;
        if (orderId === undefined) {
          orderId = '';
        }
        var order = {
          orderId: orderId,
          supplier: '',
          technology: '',
          flowCycle: undefined,
          unitPrice: undefined,
          valuationUint: '付',
          maching: '',
          hasEle: false,
          canEle: true,
          remark: ''
        };
        return order;
      },

      checkApprovalAuthority: function () {
        var self = this;
        return ajaxRequest('putOutNew/checkPutOutApprovalPermission', {}, false).then(function (res) {
          var hasApproval = res.result;
          self.hasApproval = hasApproval;
          return hasApproval;
        });
      },

      orderChange: function () {
        var order = this.order;
        var orderId = order.orderId;
        if (orderId === '') {
          return;
        }

        var orderList = this.orderList;
        var selectOrder = _.find(orderList, {
          orderId: orderId
        });
        this.selectOrder = selectOrder;

        this.orderLoading = true;
        var self = this;
        Promise.all([
          this.setDetailList(orderId),
          this.setEleOrderData(orderId)
        ]).then(function () {
          self.setMachiningList(orderId).then(function () {
            self.orderLoading = false;
            self.orderDetail = [];
          });
        }).catch(function () {
          self.orderLoading = false;
          self.machingList = [];
          self.order.maching = '';
          self.order.hasEle = false;
          self.order.canEle = true;
          self.orderDetail = [];
        });
      },

      supplierChange: function () {
        var order = this.order;
        var supplier = order.supplier;
        if (supplier === '') {
          return;
        }

        this.technologyLoading = true;
        var self = this;
        this.setProdCycleList(supplier.id).then(function () {
          self.order.technology = '';
          self.technologyLoading = false;
        }).catch(function () {
          self.technologyLoading = false;
        });
      },

      technologyChange: function () {
        var order = this.order;
        var prodCycleList = this.prodCycleList;
        if (prodCycleList.length === 0) {
          this.order.flowCycle = undefined;
          return;
        }

        var prodCycle = _.find(prodCycleList, {
          technology: order.technology
        });
        if (prodCycle === undefined) {
          this.order.flowCycle = undefined;
          this.order.unitPrice = undefined;
        } else {
          this.order.flowCycle = prodCycle.flowCycle;
          this.order.unitPrice = prodCycle.unitPrice;
        }
      },

      machingChange: function () {
        var order = this.order;
        var maching = order.maching;
        var detailList = this.detailList;
        if (maching.indexOf('machineMap-') === 0) {
          var materialMachingMap = this.materialMachingMap;
          var type = maching.split('-')[1];
          var obj = materialMachingMap[type];
          if (obj === undefined) {
            detailList = [];
          } else {
            var materialTypeList = obj.materialTypeList;
            detailList = _.filter(detailList, function (detail) {
              var materialType = detail.materialType;
              return materialTypeList.indexOf(materialType) !== -1;
            });
          }
        } else if (maching !== 'all') {
          detailList = _.filter(detailList, {
            materialType: maching
          });
        }

        var selectable = ModuleUtil.getEleOrderSelect(detailList, maching, this.eleOrderData);
        order.canEle = selectable.canEle;
        if (!selectable.canEle) {
          order.hasEle = selectable.hasEle;
        }
        this.orderDetail = detailList;
      },

      setProdCycleList: function (supplierId) {
        var self = this;
        return ajaxRequest('putOutNew/getPutoutFlowCycle', {
          supplierId: supplierId,
          status: 1
        }).then(function (res) {
          var prodCycleList = res.returnData;
          self.prodCycleList = prodCycleList;
          return prodCycleList;
        }).catch(function () {
          return [];
        });
      },

      setMaterialMachingMap: function () {
        var self = this;
        return ModuleUtil.getMaterialMachingInfoMap().then(function (materialMachingMap) {
          self.materialMachingMap = materialMachingMap;
          return materialMachingMap;
        }).catch(function () {
          return {};
        });
      },

      setOrderList: function () {
        var self = this;
        return ajaxRequest('weiXin/getOrderList').then(function (orders) {
          orders = _.filter(orders, {
            status: 1
          });
          self.orderList = orders;
          return orders;
        }).catch(function () {
          return [];
        });
      },

      setSupplierList: function () {
        var self = this;
        return SysUtil.getSupplierDropDown().then(function (supplierList) {
          self.supplierList = supplierList;
          return supplierList;
        }).catch(function () {
          return [];
        });
      },

      setDetailList: function (orderId) {
        var self = this;
        return ajaxRequest('putOutNew/getOrderInfoDetail', {
          orderId: orderId
        }).then(function (detailList) {
          for (var i = 0; i < detailList.length; i++) {
            var detail = detailList[i];
            var orderTotal = detail.orderTotal;
            if (orderTotal !== null) {
              detail.orderTotal = Number(orderTotal);
            }
          }
          self.detailList = detailList;
        }).catch(function () {
          self.detailList = [];
          return [];
        });
      },

      setEleOrderData: function (orderId) {
        var self = this;
        return ModuleUtil.getEleOrderData(orderId).then(function (eleOrderData) {
          self.eleOrderData = eleOrderData;
          return eleOrderData;
        });
      },

      setMachiningList: function (orderId) {
        var self = this;
        return OrderApi.getOutOrderMachiningList(orderId).then(function (machingList) {
          self.machingList = machingList;
          self.order.maching = '';
          self.order.hasEle = false;
          self.order.canEle = true;
          return machingList;
        }).catch(function () {
          return [];
        });
      },

      orderFilterMehod: function (options, queryValue) {
        if (queryValue === '') {
          return options;
        }

        queryValue = queryValue.toLowerCase();
        var filterParams = ['orderId', 'companyOrderId', 'factoryId', 'customerId'];
        options = _.filter(options, function (option) {
          for (var i = 0; i < filterParams.length; i++) {
            var filterParam = filterParams[i];
            var value = _.get(option, filterParam, '');
            if (value === null) {
              value = '';
            }
            if (typeof value === 'string') {
              value = value.toLowerCase();
            }
            if (value.indexOf(queryValue) !== -1) {
              return true;
            }
          }
          return false;
        });
        return options;
      },

      createOrder: function (isAduit) {
        var order = this.order;
        var postData = this.getOrderObject(order);
        if (postData === null) {
          return;
        }

        var maching = order.maching;
        var type;
        if (maching === 'all') {
          type = -1;
        } else if (maching.indexOf('machineMap-') === 0) {
          type = maching.split('-')[1];
          type = Number(type);
        } else {
          type = 0;
        }
        postData = _.map(postData.colorList, function (color) {
          var obj = _.cloneDeep(postData);
          delete obj.colorList;
          color = _.cloneDeep(color);
          _.assignIn(obj, color);
          obj.type = type;
          return obj;
        });

        this.loading = true;
        var self = this;
        ajaxRequest('putOutNew/addPutoutOrder', {
          putoutOrderArray: JSON.stringify(postData),
          isAduit: isAduit
        }).then(function (msg) {
          if (typeof msg === 'string' && msg !== '') {
            self.$alert(msg, '信息', {
              callback: function () {
                if (self.canSelectOrder) {
                  self.resetData();
                }
                self.$emit('save-success', order);
              }
            });
          }
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      resetData: function () {
        this.order = this.getInitOrder();
        this.selectOrder = null;
        this.detailList = [];
        this.orderDetail = [];
        this.prodCycleList = [];
      },

      getOrderObject: function (order) {
        var postData = {};
        var checkFields = ["orderId", "supplier", "technology", "flowCycle", "maching", "valuationUint"];
        for (var i = 0; i < checkFields.length; i++) {
          var field = checkFields[i];
          var value = order[field];
          if (value === undefined || value === null || value === '') {
            var msg = i18n.getMsg(`orderCirculation.createOutOrder.${field}`);
            this.$alert(msg, '提示');
            return null;
          } else {
            postData[field] = value;
          }
        }

        var supplier = order.supplier;
        delete postData.supplier;
        postData.supplierId = supplier.id;
        postData.supplierName = supplier.supplierName;

        var colors = null;
        if (order.hasEle) {
          colors = this.$refs.electroplateOrder.getPostData();
        } else {
          colors = this.$refs.materialOrder.getPostData();
        }
        if (colors === null) {
          return null;
        }

        postData.colorList = colors;

        if (order.remark !== '') {
          postData.remark = order.remark;
        }

        return postData;
      }
    },
    components: {
      PageSelect: PageSelect,
      MaterialOutOrder: MaterialOutOrder(true),
      ElectroplateOutOrder: ElectroplateOutOrder
    },

    template: template
  };
}();
